﻿using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Aribaccio.Device
{
    /// <summary>
    /// Modbus配置属性
    /// </summary>
    public class ModbusSlave
    {
        /// <summary>
        /// 地址域/起始/头
        /// </summary>
        public int SlaveAddress { get; set; }
        /// <summary>
        /// 功能码
        /// </summary>
        public int FunctionCode { get; set; }
        /// <summary>
        /// 寄存器地址/起始地址
        /// </summary>
        public int RegisterAddress { get; set; }
        /// <summary>
        /// 校验方式
        /// </summary>
        public DeviceCheck CheckType { get; set; }

        /// <summary>
        /// 默认构造函数
        /// </summary>
        public ModbusSlave()
        {
            this.SlaveAddress = 0x01;
            this.RegisterAddress = 0x00;
            this.CheckType = DeviceCheck.CRC;
        }

        /// <summary>
        /// 默认构造函数
        /// </summary>
        public ModbusSlave(int argSlaveAddress, int argFunctionCode, int argRegisterAddress, DeviceCheck argCheckType = DeviceCheck.CRC)
        {
            this.SlaveAddress = argSlaveAddress;
            this.FunctionCode = argFunctionCode;
            this.RegisterAddress = argRegisterAddress;
            this.CheckType = argCheckType;
        }

        /// <summary>
        /// 
        /// </summary>
        public string ToStringHex()
        {
            List<byte> bytes= new List<byte>();
            bytes.AddRange(((byte)this.SlaveAddress).StructToBytes());
            bytes.AddRange(((byte)this.FunctionCode).StructToBytes());
            bytes.AddRange(((ushort)this.RegisterAddress).StructToBytes());
            return string.Join(" ", Array.ConvertAll(bytes.ToArray(), x => x.ToString("X2")));
        }
    }
}
